<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ page import="java.io.IOException,
                 java.util.Calendar,
                 com.actimind.actitime.util.TimeUtils,
                 com.actimind.actitime.Keys,
                 com.actimind.actitime.calendar.CalendarLayout,
                 com.actimind.actitime.calendar.CalendarLayout"%>
<bean:define id="calPrefs" name="<%=Keys.CALENDAR_PREFS_BEAN_KEY%>" type="com.actimind.actitime.beans.CalendarPrefsBean"/>

<%
    int minYear = TimeUtils.getStartYearForDropDown();
    int maxYear = TimeUtils.getEndYearForDropDown(0);
    //Comment by valet:
    //  don't include the 'Years' section (above) into declaration block (below),
    //  because maxYear will became static until next TimeTracker restart and
    //  in case you don't restart it for several years, maxYear variable
    //  will be several years past.
%>

<%!

    public static final String[] Months = new String[] {
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December"
    };

    public static void printDayOptions( JspWriter out, int curDay )
        throws  IOException
    {
        for(int i = 1; i <= 31; i++)
        {
            out.print("<option value=");
            out.print(i);
            if(curDay == i)
                out.print( " selected" );
            out.print(">");
            out.print(i);
            out.print("</option>");
        }
    }

    public static void printMonthOptions( JspWriter out, int curMonth )
        throws  IOException
    {
        for(int i = 0; i <= 11; i++)
        {
            out.print("<option value=");
            out.print(i);
            if(curMonth == i)
                out.print( " selected" );
            out.print(">");
            out.print( Months[i] );
            out.print("</option>");
        }
    }

    public static void printMonthOptionsEx( JspWriter out, int curMonth, int StartMonth, int EndMonth )
        throws  IOException
    {
        for(int i = StartMonth-1; i <= EndMonth-1; i++)
        {
            out.print("<option value=");
            out.print(i);
            if(curMonth == i)
                out.print( " selected" );
            out.print(">");
            out.print( Months[i] );
            out.print("</option>");
        }
    }

    public static void printYearOptions( JspWriter out, int minYear, int maxYear, int curYear )
        throws  IOException
    {
        for(int i = minYear; i <= maxYear; i++)
        {
            out.print("<option value=");
            out.print(i);
            if(curYear == i)
                out.print( " selected" );
            out.print(">");
            out.print(i);
            out.print("</option>");
        }
    }
%>
<script language="JavaScript">
    <!--
    var CALENDAR_IMGDIR_URL = "../img";
    var CALENDAR_CSSFILE_URL = "../css/calendar.css";

    <%
    Calendar cal = TimeUtils.getCalendar();
    if(CalendarLayout.US_WEEK_CODE.equals(calPrefs.getCalendarLayout()))
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    else
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    %>
    var curWeekStart = new Date(<%=cal.get( Calendar.YEAR )%>, 
                                <%=cal.get( Calendar.MONTH )%>,
                                <%=cal.get( Calendar.DAY_OF_MONTH )%>);
    var curMonthStart = new Date(<%=cal.get( Calendar.YEAR )%>,
                                 <%=cal.get( Calendar.MONTH )%>,
                                 1);
    var fromDate;
    var toDate;

    function updateDates(newFromDate, newToDate)
    {
        var ind = newFromDate.getFullYear() - <%=minYear%>;
        if ( ind >=0 && ind < document.forms[0].fromYear.options.length )
        {
            document.forms[0].fromYear.selectedIndex  = ind;
        }
        else
        {
            return;
        }
        var ind = newToDate.getFullYear() - <%=minYear%>;
        if ( ind >=0 && ind < document.forms[0].toYear.options.length )
        {
            document.forms[0].toYear.selectedIndex  = ind;
        }
        else
        {
            return;
        }
        document.forms[0].fromDay.selectedIndex   = newFromDate.getDate() - 1;
        document.forms[0].toDay.selectedIndex     = newToDate.getDate() - 1;
        document.forms[0].fromMonth.selectedIndex = newFromDate.getMonth();
        document.forms[0].toMonth.selectedIndex   = newToDate.getMonth();
        fromDate = newFromDate;
        toDate = newToDate;
    }

    function setToCurrentWeek()
    {
        var newFromDate = curWeekStart;
        var newToDate = new Date(newFromDate);
        newToDate.setDate(newFromDate.getDate() + 6);
        updateDates(newFromDate, newToDate);
    }

    function setToPrevWeek()
    {
        var newFromDate = getWeekStart(fromDate);
        newFromDate.setDate(newFromDate.getDate() - 7);
        var newToDate = new Date(newFromDate);
        newToDate.setDate(newToDate.getDate() + 6);
        updateDates(newFromDate, newToDate);
    }

    function setToNextWeek()
    {
        var newFromDate = getWeekStart(fromDate);
        newFromDate.setDate(newFromDate.getDate() + 7);
        var newToDate = new Date(newFromDate);
        newToDate.setDate(newToDate.getDate() + 6);
        updateDates(newFromDate, newToDate);
    }

    function getWeekStart(date)
    {
        var weekStart = new Date(curWeekStart);
        if(date < curWeekStart)
        {
            while(date < weekStart)
                weekStart.setDate(weekStart.getDate() - 7);
            return weekStart;
        }
        else
        {
            while(date >= weekStart)
                weekStart.setDate(weekStart.getDate() + 7);
            weekStart.setDate(weekStart.getDate() - 7);
            return weekStart;
        }
    }

    function setToCurrentMonth()
    {
        var newFromDate = curMonthStart;
        var newToDate = new Date(newFromDate);
        addMonth(newToDate, 1);
        newToDate.setDate(0);
        updateDates(newFromDate, newToDate);
    }

    function setToPrevMonth()
    {
        var newFromDate = new Date(fromDate);
        addMonth(newFromDate, -1);
        newFromDate.setDate(1);
        var newToDate = new Date(newFromDate);
        addMonth(newToDate, 1);
        newToDate.setDate(0);
        updateDates(newFromDate, newToDate);
    }

    function addMonth(d, n)
    {
        var step;
        var len;
        var day;
        if(n > 0)
        {
            step = 28;
            len = n;
            day = 28;
        }
        else
        {
            step = -28;
            len = -n;
            day = 1;
        }
        for(i = 0; i < len; i++)
        {
            var orig = new Date(d);
            d.setDate(day);
            d.setDate(d.getDate() + step);
            var m = d.getMonth();
            d.setDate(orig.getDate());
            if(d.getMonth() != m)
                d.setDate(d.getDate() - 1);
            if(d.getMonth() != m)
                d.setDate(d.getDate() - 1);
            if(d.getMonth() != m)
                d.setDate(d.getDate() - 1);
            if(isLastDateOfMonth(orig))
            {
                d.setDate(d.getDate() + 4);
                d.setDate(0);
            }
        }
    }

    function isLastDateOfMonth(d)
    {
        var t = new Date(d);
        t.setDate(t.getDate() + 1);
        return t.getMonth() != d.getMonth();
    }

    function setToNextMonth()
    {
        var newFromDate = new Date(fromDate);
        addMonth(newFromDate, 1);
        newFromDate.setDate(1);
        var newToDate = new Date(newFromDate);
        addMonth(newToDate, 1);
        newToDate.setDate(0);
        updateDates(newFromDate, newToDate);
    }

    function getDateWithPrefix(prefix)
    {
        var year  = document.forms[0].elements[prefix + "Year"];
        var month = document.forms[0].elements[prefix + "Month"];
        var day   = document.forms[0].elements[prefix + "Day"];

        with(document.forms[0])
        {
            var tmp = new Date(getVal(year), getVal(month), getVal(day));

            while (tmp.getMonth() != getVal(month)) /* Non-existing date */
            {
                day.selectedIndex --;
                tmp = new Date(getVal(year), getVal(month), getVal(day));
            }
            return tmp;
        }
    }

    function synchronize()
    {
        fromDate = getDateWithPrefix('from');
        toDate = getDateWithPrefix('to');
    }

    function selectFromDate(dateStr)
    {
        var newFromDate = strToDate(dateStr);
        updateDates(newFromDate, toDate);
    }

    function selectToDate(dateStr)
    {
        var newToDate = strToDate(dateStr);
        updateDates(fromDate, newToDate);
    }

    function popupCalendar(date, query)
    {
       var dateStr = dateToStr(date);
       var url = '<html:rewrite page="/calendar.do" />?';
       //
       var cWnd = window.open(url + query + '&dateStr=' + dateStr, 'popup', 'width=223,height=320,scrollbars=no,status=no,resizable=no,top=200,left=200');
       cWnd.opener = self;
       cWnd.focus();
    }
    // -->
</script>

<table border="0" cellpadding="2" cellspacing="0" width="250">
<tr>
    <td width="20"></td>
    <td width="40%"></td>
    <td width="40%"></td>
    <td></td>
</tr>
<tr>
    <td class="text" align="left" nowrap bgcolor="#E5E5E5">&nbsp;&nbsp;&nbsp;From:</td>
    <td colspan="2" align="center" nowrap bgcolor="#E5E5E5">
        <html:select property="fromMonth"  styleClass="text" onchange="synchronize();">
                     <% printMonthOptions( out, form.getFromMonth() ); %>
        </html:select>
        <html:select property="fromDay"  styleClass="text" onchange="synchronize();">
                     <% printDayOptions( out, form.getFromDay() ); %>
        </html:select>
        <html:select property="fromYear"  styleClass="text" onchange="synchronize();">
                     <% printYearOptions( out, minYear, maxYear, form.getFromYear() ); %>
        </html:select>
        <%
            int yearFrom = TimeUtils.getStartYearForDropDown();
            int yearTo = TimeUtils.getEndYearForDropDown(0);
        %>
        <a href="javascript:popupCalendar(fromDate, 'yearFrom=<%=yearFrom%>&yearTo=<%=yearTo%>&selectDate=selectFromDate');"><img src="../img/cal.gif" width="20" height="20" border="0" alt="Click Here to Pick up the date"></a>
    </td>
    <td><input type="button" value="Set Current Month" onclick="setToCurrentMonth();" style="width: 120px"></td>
</tr>
<tr>
    <td class="text" align="left" nowrap bgcolor="#E5E5E5">&nbsp;&nbsp;&nbsp;To:</td>
    <td colspan="2" valign="center" align="center" nowrap bgcolor="#E5E5E5">
        <html:select property="toMonth"  styleClass="text" onchange="synchronize();">
                     <% printMonthOptions( out, form.getToMonth() ); %>
        </html:select>
        <html:select property="toDay"  styleClass="text" onchange="synchronize();">
                     <% printDayOptions( out, form.getToDay() ); %>
        </html:select>
        <html:select property="toYear"  styleClass="text" onchange="synchronize();">
                     <% printYearOptions( out, minYear, maxYear, form.getToYear() ); %>
        </html:select>

        <a href="javascript:popupCalendar(toDate, 'yearFrom=<%=yearFrom%>&yearTo=<%=yearTo%>&selectDate=selectToDate');"><img src="../img/cal.gif" width="20" height="20" border="0" alt="Click Here to Pick up the date"></a>
    </td>
    <td><input type="button" value="Set Current Week" onclick="setToCurrentWeek();" style="width: 120px"></td>
</tr>
<tr>
    <td colspan="2"  nowrap="1">
        <input type="button" value="< Month" onclick="setToPrevMonth();">
        <input type="button" value="< Week" onclick="setToPrevWeek();">
    </td>
    <td align="right" nowrap="1">
        <input type="button" value="Week >" onclick="setToNextWeek();">
        <input type="button" value="Month >" onclick="setToNextMonth();">
    </td>
    <td>&nbsp;</td>
</tr>
</table>
<script language="JavaScript">
<!--
    synchronize();
// -->
</script>